import { cloneAndReplaceKey } from './ReactElement'

function mapChildren(children, func, context) {
  // TODO实现此mapChildren方法
  if (children == null) {
    return children
  }
  const result = []
  mapIntoArray(children, result, '', func)
  return result
}

let count = 0
function mapIntoArray(children, array, escapedPrefix, callback) {
  const type = typeof children

  if (type === 'undefined' || type === 'boolean') {
    children = null
  }

  for (let i = 0; i < children.length; i++) {
    const element = children[i]
    if (element.length > 0) {
      mapIntoArray(element, array, i, callback)
    } else {
      let preKey = ''
      if (element.key) {
        preKey = element.key
      }
      let res = callback(element, count)

      let res2 = res.map((item) => {
        let key = handleKey(item, count, preKey, escapedPrefix)
        return cloneAndReplaceKey(item, key)
      })

      count++
      array.push(...res2)
    }
  }
}

// 总的来说就是要评Key，我这个写法好像是只能满足一层数组，如果是多层数组，比如：[a,[a,[a,a]]],我这个方法应该就会出问题
// 源码中好像是用正则去实现这个问题的，但是我还没看明白，还要再去研究研究……
function handleKey(element, count, preKey, escapedPrefix) {
  let key = ''

  if (preKey !== '') {
    key += `.$${preKey}/`
  } else {
    key += `.${count}/`
  }

  if (element.key) {
    key = `${key}.$${element.key}`
  }

  if (escapedPrefix !== '') {
    key = `.${escapedPrefix}:${key}`
  }
  console.log(key)
  return key
}

export { mapChildren as map }

// .0/.$div0A
// .0/.$div0B
// .$key2/.$div1A
// .$key2/.$div1B
// .$key3/.$div2A
// .$key3/.$div2B
// .3:$key4/.$div3A
// .3:$key4/.$div3B
// .3:$key5/.$div4A
// .3:$key5/.$div4B
// .3:$key6/.$div5A
// .3:$key6/.$div5B
